import importlib
import inspect
import sys
import os

from plugins.plugin import Plugin

class PMan:

    def __init__(self, config=None):
        self.config = config
        self.plugins = list()
        self.extension = '.py'
        self.plugins_dir = os.path.dirname(self.config.config_path) + "/plugins"
        sys.path.append(self.plugins_dir)
         
    def inspect_obj(self, obj) -> bool:
        return inspect.isclass(obj) and issubclass(obj, Plugin) and obj != Plugin

    def add_plugin_from_module(self, pfile) -> None:
        for it in dir(pfile):
            obj = getattr(pfile, it)
            if self.inspect_obj(obj):
                plugin = obj(config=self.config)
                self.plugins.append(plugin)
                plugin.id = len(self.plugins)-1

    def load_user_plugin(self, fname) -> None:
        pfile = importlib.import_module(fname)
        self.add_plugin_from_module(pfile) 

    def load_plugins(self) -> None:
        print("#=====> Init plugins <=====#")
        for file in os.listdir(self.plugins_dir):
            if file.endswith(self.extension):
                file = file[:-3]

                print(f"    Init plugin: {file}...")
                
                pfile = importlib.import_module(file)
                self.add_plugin_from_module(pfile)
        print("#==========================#")
                
    def remove_plugin(self, name) -> str:
        path = f"{self.plugins_dir}/{name}.py"
        if not os.path.exists(path): return f"Error: {name} plugin not found!"
        os.remove(path)

        return f"OK: {name} plugin removed!"
    
    def print_plugins(self) -> None:
        for plugin in self.plugins:
            print(plugin.name)

    def get_plugin_by_name(self, name) -> (Plugin | None):
        for plugin in self.plugins:
            if plugin.name == name: return plugin

    def get_plugin_by_id(self, id) -> (Plugin | None):
        for plugin in self.plugins: 
            if plugin.id == id: return plugin

if __name__ == "__main__":
    pm = PMan()
    pm.print_plugins()




